﻿using System.Collections.Generic;
using Contracts.Entities;

namespace Model.MovieElements
{
    public abstract class WriteMovieElement
    {
        protected MovieDatabaseEntities entities;
        protected SynchronizeMovieElements sync;
        protected Movies movie;

        public WriteMovieElement(MovieDatabaseEntities entities, Movies movie)
        {
            this.entities = entities;
            this.movie = movie;
            this.sync = new SynchronizeMovieElements();
            this.sync.OnCompleted += Update;
        }

        public void Process(IEnumerable<MovieElement> items)
        {
            IEnumerable<MovieElement> dbItems = null;

            switch (GetMovieElementType())
            {
                case MovieElementType.Actor: dbItems = ActorConverter.GetElements(movie.Actors); break;
                case MovieElementType.Director: dbItems = DirectorConverter.GetElements(movie.Directors); break;
                case MovieElementType.Country: dbItems = CountryConverter.GetElements(movie.Countries); break;
                case MovieElementType.Genre: dbItems = GenreConverter.GetElements(movie.Genres); break;
                case MovieElementType.Studio: dbItems = StudioConverter.GetElements(movie.Studios); break;
            }
 
            sync.Process(dbItems, items);
        }

        public void Update(IEnumerable<MovieElement> elements)
        {
            foreach (var element in elements)
            {
                switch (element.SyncState)
                {
                    case SyncState.Inserted: Insert(element);
                        break;
                    case SyncState.Deleted: Delete(element);
                        break;
                }
            }
        }

        public abstract void Insert(MovieElement element);

        public abstract void Delete(MovieElement element);

        public abstract MovieElementType GetMovieElementType();
    }
}
